package com.spring.common.manageException;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;


import com.spring.authManage.pojo.UserInfo;
import com.spring.common.manageException.pojo.ExceptionInfo;
import com.spring.common.manageException.service.ExceptionService;
import com.spring.common.util.ExceptionUtil;


public class ExceptionHandler implements HandlerExceptionResolver{

	@Autowired
	private ExceptionService exceptionService;
	
	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object obj1, Exception exception) {
		// TODO Auto-generated method stub
		
		HttpSession session = request.getSession();
		UserInfo user = (UserInfo)session.getAttribute("user");
		String userName = "";
		if(user!=null){
			userName = user.getUserName();
		}else{
			userName = "unknow";
		}
		String client = "PC REQUEST:";
		String requestType = request.getHeader("X-Requested-With");
		if(requestType!=null&&"XMLHttpRequest".equals(requestType)){
			client = "MOBILE REQUEST:";
		}
		ExceptionInfo exp = new ExceptionInfo();
		exp.setUserName(userName);
		exp.setInfo(client + ExceptionUtil.getStackTrace(exception));
		this.exceptionService.recordException(exp);
		exception.printStackTrace();
		
		if("PC REQUEST:".equals(client)){
			return new ModelAndView("error/error");
		}else{
			try {
				response.getWriter().write("<script>alert('系统异常')</script>");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
	}

}
